package com.chushouya.product.task;

import com.chushouya.product.dao.entity.ProductEntity;
import com.chushouya.product.service.common.ProductImageGenerateService;
import com.general.framework.job.starter.TaskUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 产品列表图片生成任务
 * 根据指定的分类和品牌生成产品列表图片
 */
@Component
@Slf4j
public class ProductImageGenerateTask {

    @Resource
    private ProductImageGenerateService productImageGenerateService;

    /**
     * 生成产品列表图片任务
     * 参数格式: categoryId,brandId,title
     * 示例1: 1,2,出手鸭苹果手机回收最新行情  (生成指定分类和品牌的图片)
     * 示例2: 1,,出手鸭产品回收最新行情       (生成指定分类下所有品牌的图片)
     * 
     * categoryId: 分类ID (必填)
     * brandId: 品牌ID (可选，为空则生成该分类下所有品牌的图片)
     * title: 图片标题 (可选，默认为"出手鸭产品回收最新行情")
     */
    @XxlJob(value = "productImageGenerateJobHandler")
    public ReturnT<String> productImageGenerateJobHandler() {
        final String jobName = "产品列表图片生成";
        String param = XxlJobHelper.getJobParam();
        final Long startTime = TaskUtil.taskStart(jobName, param);

        try {
            ImageGenerateParam imageParam = new ImageGenerateParam(param).invoke();
            
            if (imageParam.getCategoryId() == null) {
                log.error("参数错误: categoryId不能为空");
                TaskUtil.taskEnd(jobName, param, startTime);
                return ReturnT.FAIL;
            }

            // 判断是生成单个品牌还是所有品牌
            if (imageParam.getBrandId() != null) {
                // 生成指定品牌的图片
                return generateSingleBrandImage(imageParam, jobName, param, startTime);
            } else {
                // 生成该分类下所有品牌的图片
                return generateAllBrandsImage(imageParam, jobName, param, startTime);
            }

        } catch (Exception e) {
            log.error("产品列表图片生成任务执行失败", e);
            TaskUtil.taskEnd(jobName, param, startTime);
            return ReturnT.FAIL;
        }
    }

    /**
     * 生成指定分类和品牌的单个图片
     */
    private ReturnT<String> generateSingleBrandImage(ImageGenerateParam imageParam, String jobName, String param, Long startTime) {
        try {
            log.info("开始生成单个品牌图片, categoryId: {}, brandId: {}", imageParam.getCategoryId(), imageParam.getBrandId());
            
            // 查询产品列表
            List<ProductEntity> products = productImageGenerateService.getProductListByCategoryAndBrand(
                    imageParam.getCategoryId(), 
                    imageParam.getBrandId()
            );

            if (products == null || products.isEmpty()) {
                log.warn("未查询到产品数据, categoryId: {}, brandId: {}", 
                        imageParam.getCategoryId(), imageParam.getBrandId());
                TaskUtil.taskEnd(jobName, param, startTime);
                return ReturnT.SUCCESS;
            }

            // 生成日期字符串
            String dateStr = new SimpleDateFormat("MM月dd日").format(new Date());

            // 生成并上传图片到OSS
            String ossUrl = productImageGenerateService.generateAndUploadProductListImage(
                    products, 
                    imageParam.getTitle(), 
                    dateStr,
                    imageParam.getCategoryId(),
                    imageParam.getBrandId()
            );

            if (ossUrl != null && !ossUrl.isEmpty()) {
                log.info("产品列表图片生成并上传OSS成功: {}, 产品数量: {}", ossUrl, products.size());
                TaskUtil.taskEnd(jobName, param, startTime);
                return ReturnT.SUCCESS;
            } else {
                log.error("产品列表图片生成或上传失败");
                TaskUtil.taskEnd(jobName, param, startTime);
                return ReturnT.FAIL;
            }

        } catch (Exception e) {
            log.error("生成单个品牌图片失败", e);
            TaskUtil.taskEnd(jobName, param, startTime);
            return ReturnT.FAIL;
        }
    }

    /**
     * 生成指定分类下所有品牌的图片
     */
    private ReturnT<String> generateAllBrandsImage(ImageGenerateParam imageParam, String jobName, String param, Long startTime) {
        try {
            log.info("开始批量生成分类下所有品牌图片, categoryId: {}", imageParam.getCategoryId());
            
            // 批量生成该分类下所有品牌的产品图片
            String result = productImageGenerateService.generateAllBrandImagesForCategory(
                    imageParam.getCategoryId(), 
                    imageParam.getTitle()
            );
            
            log.info("批量生成完成，结果: {}", result);
            TaskUtil.taskEnd(jobName, param, startTime);
            
            // 判断是否有失败的情况
            if (result.contains("失败：")) {
                return ReturnT.FAIL;
            }
            
            return ReturnT.SUCCESS;
            
        } catch (Exception e) {
            log.error("批量生成品牌图片失败", e);
            TaskUtil.taskEnd(jobName, param, startTime);
            return ReturnT.FAIL;
        }
    }

    @Data
    private class ImageGenerateParam {

        private String param;

        private Long categoryId;

        private Long brandId;

        private String title;

        private ImageGenerateParam(String param) {
            this.param = param;
        }

        private ImageGenerateParam invoke() {
            categoryId = null;
            brandId = null;
            title = "出手鸭产品回收最新行情";

            // xxl-job 手动调用传参
            // 参数格式: categoryId,brandId,title
            if (Strings.isNotBlank(param)) {
                String[] params = param.split(",", -1); // 使用 -1 保留空字符串
                
                if (params.length >= 1 && Strings.isNotBlank(params[0])) {
                    categoryId = TaskUtil.getParamId(params[0].trim());
                }
                
                if (params.length >= 2 && Strings.isNotBlank(params[1])) {
                    brandId = TaskUtil.getParamId(params[1].trim());
                }
                
                if (params.length >= 3 && Strings.isNotBlank(params[2])) {
                    title = params[2].trim();
                }
            }
            
            return this;
        }
    }
}
